package com.micro.school.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.common.core.utils.DateUtils;
import com.micro.school.common.core.utils.JwtUtils;
import com.micro.school.common.core.utils.SecurityContextHolderUtils;
import com.micro.school.common.core.utils.StringUtils;
import com.micro.school.common.security.utils.SecurityUtils;
import com.micro.school.system.api.RemoteEduService;
import com.micro.school.system.api.RemoteOrderService;
import com.micro.school.system.api.domain.StudentInfos;
import com.micro.school.system.api.domain.vo.*;
import com.micro.school.system.api.model.LoginUser;
import com.micro.school.system.domain.CampusUser;
import com.micro.school.system.domain.CollegeUser;
import com.micro.school.system.domain.vo.StudentInfoOld;
import com.micro.school.system.domain.vo.StudentPayVo;
import com.micro.school.system.mapper.CampusUserMapper;
import com.micro.school.system.mapper.CollegeUserMapper;
import com.micro.school.system.mapper.StudentPayMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.micro.school.system.mapper.StudentInfoMapper;
import com.micro.school.system.domain.StudentInfo;
import com.micro.school.system.domain.vo.StudentInfoVo;
import com.micro.school.system.convert.student.StudentInfoConvert;
import com.ruoyi.system.service.IStudentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author rakic
 * @date 2025-08-05
 */
@Service
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper,StudentInfo> implements IStudentInfoService
{
    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Resource
    private RemoteEduService remoteEduService;

    @Resource
    private CollegeUserMapper collegeUserMapper;
    @Autowired
    private CampusUserMapper campusUserMapper;


    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public StudentInfoVo selectStudentInfoById(Long id)
    {
        StudentInfoVo studentInfoVo = studentInfoMapper.selectStudentInfoById(id, Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        /*if (SecurityContextHolder.getUserIdcardState() != null) {
            if (1 == SecurityContextHolder.getUserIdcardState()) {
                if (studentInfoVo.getIdNumber() != null && studentInfoVo.getIdNumber().length() > 8) {
                    String maskedIdNumber = studentInfoVo.getIdNumber().substring(0, studentInfoVo.getIdNumber().length() - 8) + "********";
                    studentInfoVo.setIdNumber(maskedIdNumber);
                } else if (studentInfoVo.getIdNumber() != null) {
                    studentInfoVo.setIdNumber(studentInfoVo.getIdNumber().replaceAll(".", "*"));
                }

            }
        }*/
        return studentInfoVo;
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param studentInfoVo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<StudentInfo> selectStudentInfoList(StudentInfoVo studentInfoVo)
    {
        studentInfoVo.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            studentInfoVo.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            String userCollegeId = SecurityContextHolder.getUserCollegeId();
            if (!StringUtils.isEmpty(userCollegeId)) {
                studentInfoVo.setCollegeIdList(userCollegeId);
            }
        }
        studentInfoVo.setIsDel(0);
        List<StudentInfo> studentInfoVos = studentInfoMapper.selectStudentInfoList(studentInfoVo);
        if (SecurityContextHolder.getUserIdcardState() != null){
            if (1 == SecurityContextHolder.getUserIdcardState()){
                studentInfoVos.forEach(vo -> {
                    if (vo.getIdNumber() != null && vo.getIdNumber().length() > 8) {
                        String maskedIdNumber = vo.getIdNumber().substring(0, vo.getIdNumber().length() - 8) + "********";
                        vo.setIdNumber(maskedIdNumber);
                    } else if (vo.getIdNumber() != null) {
                        vo.setIdNumber(vo.getIdNumber().replaceAll(".", "*"));
                    }
                });
            }
        }
        return studentInfoVos;
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param studentInfoVo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public String insertStudentInfo(StudentInfoVo studentInfoVo)
    {
        StudentInfo studentInfo = StudentInfoConvert.convertToInfo(studentInfoVo);

        studentInfo.setCreateTime(DateUtils.getNowDate());
        studentInfo.setIsDel(0);
        studentInfo.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));

        StudentInfoVo studentInfo1 = new StudentInfoVo();
        studentInfo1.setIdNumber(studentInfoVo.getIdNumber());
        studentInfo1.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));


        SchoolCollegeVos schoolCollegeVos1 = new SchoolCollegeVos();
        schoolCollegeVos1.setId(studentInfoVo.getCollegeId());
        schoolCollegeVos1.setDeleteFlag("0");
        R<List<SchoolCollegeVos>> schoolCollegeVosList = remoteEduService.checkCollege(schoolCollegeVos1);
        if (schoolCollegeVosList.getData() != null && schoolCollegeVosList.getData().size() > 0) {
            studentInfo.setCompusId(Math.toIntExact(schoolCollegeVosList.getData().get(0).getCampusId()));
        }

        List<StudentInfoVo> studentInfoVos = studentInfoMapper.selectStudentInfotoList(studentInfo1);
        if (studentInfoVos != null && studentInfoVos.size() > 0){
            return "身份证已被录入过，请重新输入";
        }else{
            studentInfo.setSignTime(new Date());
            SchoolCollegeVos schoolCollegeVos = new SchoolCollegeVos();
            schoolCollegeVos.setId(studentInfoVo.getCollegeId());
            schoolCollegeVos.setDeleteFlag("0");
            R<List<SchoolCollegeVos>> listR = remoteEduService.checkCollege(schoolCollegeVos);
            if (listR.getData() != null && listR.getData().size() > 0) {
                studentInfo.setCollegeName(listR.getData().get(0).getCollegeName());
            }
            SchoolGradeVos schoolGradeVos = new SchoolGradeVos();
            schoolGradeVos.setId(studentInfoVo.getGradeId());
            schoolGradeVos.setDeleteFlag("0");
            schoolGradeVos.setStatus("1");
            R<List<SchoolGradeVos>> listGradeVo = remoteEduService.checkGrade(schoolGradeVos);
            if (listGradeVo.getData() != null && listGradeVo.getData().size() > 0) {
                studentInfo.setGradeName(listGradeVo.getData().get(0).getGrade());
            }

            CollegeModelVos collegeModelVos = new CollegeModelVos();
            collegeModelVos.setId(studentInfoVo.getEducationId());
            collegeModelVos.setDeleteFlag("0");
            collegeModelVos.setStatus("1");
            R<List<CollegeModelVos>> listR1 = remoteEduService.checkEducation(collegeModelVos);
            if (listR1.getData() != null && listR1.getData().size() > 0) {
                studentInfo.setEducation(listR1.getData().get(0).getModelName());
            }
            CollegeMajorVos collegeMajorVos = new CollegeMajorVos();
            collegeMajorVos.setId(studentInfoVo.getMajorId());
            collegeMajorVos.setDeleteFlag("0");
            collegeMajorVos.setStatus("1");
            R<List<CollegeMajorVos>> listR2 = remoteEduService.checkMajor(collegeMajorVos);
            if (listR2.getData() != null && listR2.getData().size() > 0) {
                studentInfo.setMajorName(listR2.getData().get(0).getMajorName());
            }

            SchoolCampusVos schoolCampusVos = new SchoolCampusVos();
            schoolCampusVos.setId(Long.valueOf(studentInfo.getCompusId()));
            schoolCampusVos.setDeleteFlag("0");
            schoolCampusVos.setStatus("1");
            R<List<SchoolCampusVos>> listR3 = remoteEduService.checkCampus(schoolCampusVos);
            if (listR3.getData() != null && listR3.getData().size() > 0) {
                studentInfo.setBranchName(listR3.getData().get(0).getCampusName());
            }
            studentInfo.setUpdateTime(new Date());
            studentInfoMapper.insertStudentInfo(studentInfo);
            return "";
        }
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param studentInfoVo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public String updateStudentInfo(StudentInfoVo studentInfoVo) {
        StudentInfo studentInfo = StudentInfoConvert.convertToInfo(studentInfoVo);
        studentInfo.setUpdateTime(DateUtils.getNowDate());

        // 获取学院信息
        SchoolCollegeVos schoolCollegeVos = new SchoolCollegeVos();
        schoolCollegeVos.setId(studentInfoVo.getCollegeId());
        schoolCollegeVos.setDeleteFlag("0");
        R<List<SchoolCollegeVos>> collegeResult = remoteEduService.checkCollege(schoolCollegeVos);

        if (collegeResult.getData() != null && !collegeResult.getData().isEmpty()) {
            SchoolCollegeVos collegeInfo = collegeResult.getData().get(0);
            studentInfo.setCompusId(Math.toIntExact(collegeInfo.getCampusId()));
            studentInfo.setCollegeName(collegeInfo.getCollegeName());

            // 获取年级信息
            if (studentInfoVo.getGradeId() != null) {
                SchoolGradeVos schoolGradeVos = new SchoolGradeVos();
                schoolGradeVos.setId(studentInfoVo.getGradeId());
                schoolGradeVos.setDeleteFlag("0");
                schoolGradeVos.setStatus("1");
                R<List<SchoolGradeVos>> gradeResult = remoteEduService.checkGrade(schoolGradeVos);
                if (gradeResult.getData() != null && !gradeResult.getData().isEmpty()) {
                    studentInfo.setGradeName(gradeResult.getData().get(0).getGrade());
                }
            }

            // 获取学历信息
            if (studentInfoVo.getEducationId() != null) {
                CollegeModelVos collegeModelVos = new CollegeModelVos();
                collegeModelVos.setId(studentInfoVo.getEducationId());
                collegeModelVos.setDeleteFlag("0");
                collegeModelVos.setStatus("1");
                R<List<CollegeModelVos>> educationResult = remoteEduService.checkEducation(collegeModelVos);
                if (educationResult.getData() != null && !educationResult.getData().isEmpty()) {
                    studentInfo.setEducation(educationResult.getData().get(0).getModelName());
                }
            }

            // 获取专业信息
            if (studentInfoVo.getMajorId() != null) {
                CollegeMajorVos collegeMajorVos = new CollegeMajorVos();
                collegeMajorVos.setCollegeIds(String.valueOf(collegeInfo.getId()));
                collegeMajorVos.setId(studentInfoVo.getMajorId());
                collegeMajorVos.setDeleteFlag("0");
                collegeMajorVos.setStatus("1");
                R<List<CollegeMajorVos>> majorResult = remoteEduService.checkMajor(collegeMajorVos);
                if (majorResult.getData() != null && !majorResult.getData().isEmpty()) {
                    studentInfo.setMajorName(majorResult.getData().get(0).getMajorName());
                }
            }

            // 获取校区信息
            SchoolCampusVos schoolCampusVos = new SchoolCampusVos();
            schoolCampusVos.setId(collegeInfo.getCampusId());
            schoolCampusVos.setDeleteFlag("0");
            schoolCampusVos.setStatus("1");
            R<List<SchoolCampusVos>> campusResult = remoteEduService.checkCampus(schoolCampusVos);
            if (campusResult.getData() != null && !campusResult.getData().isEmpty()) {
                studentInfo.setBranchName(campusResult.getData().get(0).getCampusName());
            }

            // 校验身份证是否重复（排除当前正在修改的学生）
            StudentInfoVo studentInfoVo1 = new StudentInfoVo();
            studentInfoVo1.setIdNumber(studentInfo.getIdNumber());
            studentInfoVo1.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));
            studentInfoVo1.setIsDel(0);
            List<StudentInfo> studentInfoVoList = studentInfoMapper.selectStudentInfoList(studentInfoVo1);

            // 如果查询到的学生信息不为空，且ID不等于当前修改的学生ID，则说明身份证重复
            if (studentInfoVoList != null && !studentInfoVoList.isEmpty()) {
                for (StudentInfo existingStudent : studentInfoVoList) {
                    if (!existingStudent.getId().equals(studentInfoVo.getId())) {
                        return "身份证号已被其他学生使用，请重新输入";
                    }
                }
            }
            studentInfoMapper.updateStudentInfo(studentInfo);
        } else {
            return "学院信息不存在";
        }

        return "";
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteStudentInfoByIds(List<Long> ids)
    {

        return studentInfoMapper.deleteStudentInfoByIds(ids,Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteStudentInfoById(Long id)
    {
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setId(id);
        studentInfo.setUpdateTime(new Date());
        studentInfo.setIsDel(1);
        studentInfo.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        return studentInfoMapper.updateStudentInfo(studentInfo);
    }

    @Override
    public int signStudentInfoByIds(StudentInfoVo studentInfoVo) {
        if(studentInfoVo.getIds() != null) {
            return studentInfoMapper.signStudentInfoByIds(studentInfoVo.getSignStatus(), Integer.parseInt(SecurityContextHolder.getUserTenantId()), studentInfoVo.getIds());
        }else{
            List<Long> ids = new ArrayList<>();
            ids.add(studentInfoVo.getId());
            return studentInfoMapper.signStudentInfoByIds(studentInfoVo.getSignStatus(), Integer.parseInt(SecurityContextHolder.getUserTenantId()), ids);
        }
    }

    @Override
    public int sealStudentInfoByIds(StudentInfoVo studentInfoVo) {
        if(studentInfoVo.getIds() != null) {
            return studentInfoMapper.sealStudentInfoByIds(studentInfoVo.getSealStatus(), studentInfoVo.getIds(),Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        }else{
            List<Long> ids = new ArrayList<>();
            ids.add(studentInfoVo.getId());
            return studentInfoMapper.sealStudentInfoByIds(studentInfoVo.getSealStatus(),ids,Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        }


    }

    @Override
    public int sealStudentInfoById(StudentInfoVo studentInfoVo) {

        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setSealStatus(studentInfoVo.getSealStatus());
        studentInfo.setSealTime(new Date());
        studentInfo.setUpdateTime(new Date());
        studentInfo.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        studentInfo.setId(studentInfoVo.getId());
        return studentInfoMapper.updateStudentInfo(studentInfo);
    }

    @Override
    public int inStudentInfoByIds(StudentInfoVo studentInfoVo) {

        return studentInfoMapper.inStudentInfoByIds(1L, studentInfoVo.getIds(), Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    @Override
    public List<StudentInfoVo> selectNewStudentInfoList(StudentInfoVo studentInfoVo) {
        studentInfoVo.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            studentInfoVo.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            String userCollegeId = SecurityContextHolder.getUserCollegeId();
            studentInfoVo.setCollegeIdList(StringUtils.isEmpty(userCollegeId) ? null: userCollegeId);
        }
        studentInfoVo.setIsDel(0);
        List<StudentInfoVo> studentInfoVos = studentInfoMapper.selectNewStudentInfoList(studentInfoVo);
        if (SecurityContextHolder.getUserIdcardState() != null){
            if (1 == SecurityContextHolder.getUserIdcardState()){
                studentInfoVos.forEach(vo -> {
                    if (vo.getIdNumber() != null && vo.getIdNumber().length() > 8) {
                        String maskedIdNumber = vo.getIdNumber().substring(0, vo.getIdNumber().length() - 8) + "********";
                        vo.setIdNumber(maskedIdNumber);
                    } else if (vo.getIdNumber() != null) {
                        vo.setIdNumber(vo.getIdNumber().replaceAll(".", "*"));
                    }
                });
            }
        }
        return studentInfoVos;
    }

    @Override
    public StudentInfos queryStudent(StudentInfoVo studentInfoVo) {
        return studentInfoMapper.queryStudent(studentInfoVo);
    }

    /**
     * 每次查询100条，按照id>某个值
     */
    @Override
    public List<StudentInfos> selectStudentInfoListLimit(StudentInfoVo studentInfoVo){
        return studentInfoMapper.selectStudentInfoListLimit(studentInfoVo);
    }

    @Override
    public List<StudentInfos> queryStudentByidNumber(String trim) {
        // 2. 缓存中没有则查询数据库
        String userTenantId = SecurityContextHolder.getUserTenantId();
        List<StudentInfos> student = studentInfoMapper.selectStudentByIdNumber(trim,userTenantId);
        return student;
    }
    /**
     * 根据ids查询学生信息
     * */
    @Override
    public List<StudentInfos> selectStudentByIds(List<Long> ids){
        String userTenantId = SecurityContextHolder.getUserTenantId();
        if(null==userTenantId || userTenantId.equals("")){
            userTenantId = "-1";
        }
        return studentInfoMapper.selectStudentByIds(Integer.parseInt(userTenantId),ids);
    }

    @Override
    public List<StudentInfoOld> selectOldStudentInfoList(StudentInfoVo studentInfoVo) {
        if (!SecurityContextHolder.getUserName().contains("admin")) {
            studentInfoVo.setCampusIds(SecurityContextHolderUtils.getCampusId() != null && SecurityContextHolderUtils.getCampusId().length > 0 ? SecurityContextHolderUtils.getCampusId(): null);
            String userCollegeId = SecurityContextHolder.getUserCollegeId();
            studentInfoVo.setCollegeIdList(StringUtils.isEmpty(userCollegeId) ? null: userCollegeId);
        }
        studentInfoVo.setIsDel(0);
        List<StudentInfoOld> studentInfoVos = studentInfoMapper.selectOldStudentInfoList(studentInfoVo);
        if (SecurityContextHolder.getUserIdcardState() != null){
            if (1 == SecurityContextHolder.getUserIdcardState()){
                studentInfoVos.forEach(vo -> {
                    if (vo.getIdNumber() != null && vo.getIdNumber().length() > 8) {
                        String maskedIdNumber = vo.getIdNumber().substring(0, vo.getIdNumber().length() - 8) + "********";
                        vo.setIdNumber(maskedIdNumber);
                    } else if (vo.getIdNumber() != null) {
                        vo.setIdNumber(vo.getIdNumber().replaceAll(".", "*"));
                    }
                });
            }
        }
        return studentInfoVos;
    }

    @Override
    public List<StudentInfoVos> queryVosByIdNumber(StudentInfoVos studentInfoVo) {
        return studentInfoMapper.queryVosByIdNumber(studentInfoVo);
    }

    @Override
    public int updateAllStudentInfoCollegeName(String collegeName, Long collegeId,String oldCollegeName) {
        List<CollegeUser> collegeUserList = collegeUserMapper.selectSysCollege(collegeId);
        if (collegeUserList != null && collegeUserList.size() > 0) {
            for (CollegeUser collegeUser : collegeUserList) {
                collegeUser.setCollegeName(collegeUser.getCollegeName().replace(oldCollegeName, collegeName));
            }
            collegeUserMapper.updateBatch(collegeUserList);
        }
        return studentInfoMapper.updateAllStudentInfoCollegeName(collegeName,collegeId);
    }

    @Override
    public int updateAllCollegeMajor(String majorName, Long id, String oldMajorName) {
        return studentInfoMapper.updateAllCollegeMajor(majorName,id);
    }

    @Override
    public int updateAllCollegeModel(String modelName, Long id, String oldModelName) {
        return studentInfoMapper.updateAllCollegeModel(modelName,id);
    }

    @Override
    public int updateAllCampusName(String campusName, Long id, String oldCampusName) {
        List<CampusUser> campusUserList = campusUserMapper.selectCampusUser(id);
        if (campusUserList != null && campusUserList.size() > 0) {
            for (CampusUser campusUser : campusUserList) {
                campusUser.setCampusName(campusUser.getCampusName().replace(oldCampusName, campusName));
            }
            campusUserMapper.updateBatch(campusUserList);
        }
        return studentInfoMapper.updateAllCampusName(campusName,id);
    }

    @Override
    public int updateAllSchoolGrade(String grade, Long id) {
        return studentInfoMapper.updateAllSchoolGrade(grade,id);
    }

}
